package com.xiaoerkeji.eshop.utils;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.xiaoerkeji.eshop.R;

import java.io.IOException;
import java.io.InputStream;


public class ScanActivity extends AppCompatActivity {
    private DecoratedBarcodeView barcodeView;
    private CaptureManager captureManager;
    private static final int PICK_IMAGE_REQUEST = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_barcode_scanner);

        // 初始化扫码视图
        barcodeView = findViewById(R.id.barcode_scanner);

        // 初始化CaptureManager
        captureManager = new CaptureManager(this, barcodeView);
        captureManager.initializeFromIntent(getIntent(), savedInstanceState);
        captureManager.decode();

        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());

        // 闪光灯按钮
        findViewById(R.id.btn_flash).setOnClickListener(v -> finish());

        // 选择图片按钮
        findViewById(R.id.btn_choose_image).setOnClickListener(v -> openImagePicker());
    }

    private void toggleFlash() {
//        if (barcodeView.getBarcodeView().isTorchOn()) {
//            barcodeView.getBarcodeView().setTorchOff();
//        } else {
//            barcodeView.getBarcodeView().setTorchOn();
//        }
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            decodeImageFromUri(imageUri);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void decodeImageFromUri(Uri imageUri) {
        try {
            InputStream inputStream = getContentResolver().openInputStream(imageUri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap != null) {
                int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
                bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
                RGBLuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(), pixels);
                BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

                try {
                    Result result = new MultiFormatReader().decode(binaryBitmap);
                    // 处理扫码结果
                    handleScanResult(result);
                } catch (NotFoundException e) {
                    Toast.makeText(this, "未识别到二维码", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (IOException e) {
            Toast.makeText(this, "图片读取失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private void handleScanResult(Result result) {
        // 这里处理扫码结果，可以返回到上一个Activity
        Intent intent = new Intent();
        intent.putExtra("SCAN_RESULT", result.getText());
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        captureManager.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        captureManager.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        captureManager.onSaveInstanceState(outState);
    }

}
